<template>
  <view class="container">

    <view class="nav" @tap="toHome()">
      <image :src="$xyfun.image('/static/arrow-left.png')"></image>
    </view>

    <image class="door-icon" :src="$xyfun.image('/static/store/door.png')"></image>
    <view class="room-selector">
      <text class="room-name">房间 1</text>
      <image class="arrow-down" :src="$xyfun.image('/static/store/arrow.png')"></image>
    </view>
    <view @click="toggleDoor">
      <image :src="$xyfun.image(isDoorOpen ? '/static/store/switch-on.png' : '/static/store/switch-off.png')"
        class="switch-icon"></image>
      <view class="open-door-btn">{{ isDoorOpen ? '关门' : '开门' }}</view>
    </view>

  </view>
</template>


<script>
	
	export default {
		data() {
			return {
				isDoorOpen: false, // 默认关门状态
				room_id: 1,
			};
		},
		onLoad() {
			this.getDoorStatus(); // 页面加载时获取门的状态
		},
		methods: {
			toHome() {
				uni.switchTab({
					url: "/pages/index"
				})
			},
			getDoorStatus() {
				// 获取门的状态接口
				this.$api.get({
					url: '/common/getDoorStatus',
					data: {
						room_id: this.room_id
					},
					success: res => {
						// 假设接口返回的数据为 { status: 'on' } 或 { status: 'off' }
						this.isDoorOpen = res.status === 'on';
					},
					fail: () => {
						uni.showToast({
							title: '获取门状态失败',
							icon: 'none'
						});
					}
				});
			},
			toggleDoor() {
				const newState = !this.isDoorOpen; // 切换状态

				this.$api.post({
					url: '/common/ctrlRoom',
					loadingTip: '加载中...',
					data: {
						room_id: this.room_id,
						switch: newState ? 'on' : 'off' // 接口需要 'on' 或 'off'
					},
					success: res => {
						this.isDoorOpen = newState; // 根据操作成功后更新状态
						uni.showToast({
							title: '操作成功'
						});
					},
					fail: () => {
						uni.showToast({
							title: '操作失败',
							icon: 'none'
						});
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
		background-color: #000;
		color: #fff;
	}

	.door-icon {
		width: 291rpx;
		height: 291rpx;
	}

	.switch-icon {
		width: 237rpx;
		height: 237rpx;
	}

	.room-selector {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 80%;
		padding: 10px;
		background-color: #4CAF50;
		border-radius: 42rpx;
		margin-bottom: 40px;
		margin-top: 89rpx;
		text-align: center;
		position: relative;
	}

	.room-name {
		font-size: 18px;
		color: #fff;
		text-align: center;
		width: 100%;
	}

	.arrow-down {
		width: 48rpx;
		height: 31rpx;
		position: absolute;
		right: 109rpx;
	}

	.open-door-btn {
		width: 80%;
		padding: 15px;
		font-size: 24px;
		cursor: pointer;
		color: #fff;
		text-align: center;
	}

	.nav {
		position: absolute;
		top: 20px;
		left: 10px;

		image {
			width: 25px;
			height: 25px;
		}
	}
</style>